package com.nulldev.util.web.HttpServer3.extensions.sse;

import java.util.stream.Stream;

import com.nulldev.util.data.Variables;
import com.nulldev.util.web.HttpServer3.Page;
import com.nulldev.util.web.HttpServer3.ReadRequest;

public abstract class SSEPage implements Page {

	private final String id;
	private final SSESessionManager sessionManager = new SSESessionManager();
	private final boolean prefersLowLatency;

	public SSEPage(final String id) {
		this(id, false);
	}

	public SSEPage(final String id, final boolean prefersLowLatency) {
		Variables.requireNonNull(id, "id");
		this.prefersLowLatency = prefersLowLatency;
		if (!id.startsWith("/")) {
			this.id = "/" + id.replaceAll(" ", "%20");
		} else
			this.id = id.replaceAll(" ", "%20");
	}

	public String getID() {
		return this.id;
	}

	public boolean prefersLowLatency() {
		return this.prefersLowLatency;
	}

	public SSESessionManager getSessionManager() {
		return this.sessionManager;
	}

	public Stream<SSESession> clients() {
		return this.sessionManager.clients();
	}

	public void onConnected(final SSESession sseSession, final ReadRequest rr, final String url) {
		this.sessionManager.registerSession(sseSession);
		this.sessionConnected(sseSession, rr, url);
	}

	public abstract void sessionConnected(final SSESession sseSession, final ReadRequest rr, final String url);

	public void onDisconnect(final SSESession sseSession) {
		this.sessionManager.removeSession(sseSession);
		this.sessionDisconnected(sseSession);
	}

	public abstract void sessionDisconnected(final SSESession sseSession);

	public boolean isExcludedFromCaptcha() {
		return true;
	}

}
